package com.mybatisSimpleAnnotation.demo;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

public class UnitTest {

	private static SqlSessionFactory sessionFactory;

	static {

		// mybatis的配置文件
		String resource = "config/confAnnotationVersion.xml";

		// 使用类加载器加载mybatis的配置文件
		InputStream is = UnitTest.class.getClassLoader().getResourceAsStream(resource);

		// 构建sqlSession的工厂
		sessionFactory = new SqlSessionFactoryBuilder().build(is);

	}

	
	public void testGetUser() throws IOException {
		SqlSession session = sessionFactory.openSession();
		
		IUserMapper mapper = session.getMapper(IUserMapper.class);
		
		// 执行查询返回一个唯一user对象的sql
		User user = mapper.getById(3);
		session.close();
		System.out.println("testGetUser >>> " + user);
	}

	
	public void testAdd() {

		SqlSession session = sessionFactory.openSession(true);
		
		IUserMapper mapper = session.getMapper(IUserMapper.class);

		User user = new User();
		user.setUsername("tianxiang321");
		user.setAge(20);

		// 执行插入操作
		int result = mapper.add(user);

		// 手动提交事务
		// session.commit();

		// 关闭 session
		session.close();

		System.out.println("testAdd >>> " + "add result: " + result);
	}

	
	public void testUpdate() {

		SqlSession session = sessionFactory.openSession(true);
		
		IUserMapper mapper = session.getMapper(IUserMapper.class);
		
		User user = new User();
		user.setUsername("haha");
		user.setAge(12);
		user.setId(2);
		
		int result = mapper.update(user);
		// 关闭 session
		session.close();
		System.out.println("testUpdate >>> " + "add result: " + result);
	}
	
	
	public void testDelete(){

		SqlSession session = sessionFactory.openSession(true);
		IUserMapper mapper = session.getMapper(IUserMapper.class);
		
		int result = mapper.deleteById(8);

		// 关闭 session
		session.close();
		System.out.println("testDelete >>> " + "add result: " + result);
	}
	
	@Test
	public void testGetAll(){

		SqlSession session = sessionFactory.openSession();
		IUserMapper mapper = session.getMapper(IUserMapper.class);
		
		List<User> userlist = mapper.getAll();
		
		session.close();
		System.out.println("testGetAll >>> " + userlist);
		
	}

}
